package server

import (
	"log"
)

const (
	MediaTypeVideo = "video"
	MediaTypeAudio = "audio"
)

type StreamPusher struct {
	session *RtspSession
	Tracks  []*PusherTrack

	path      string
	query     string
	sdpString string
}

func NewStreamPusher(path string, query string, sdpString string, tracks Tracks, session *RtspSession) *StreamPusher {
	c := &StreamPusher{
		session:   session,
		path:      path,
		query:     query,
		sdpString: sdpString,
	}

	for _, track := range tracks {
		if track.Media.MediaName.Media != MediaTypeVideo && track.Media.MediaName.Media != MediaTypeAudio {
			continue
		}

		if !track.hasControlAttribute() {
			log.Println("has not control attribute")
			continue
		}

		c.Tracks = append(c.Tracks, NewPusherTrack(track, c))
	}

	return c
}

func (c *StreamPusher) GetPath() string {
	if c == nil {
		return ""
	}
	return c.path
}

// GetTrackFromControl [path]/streamid=[0/1]
func (c *StreamPusher) GetTrackFromControl(trackControl string) (*PusherTrack, bool) {
	if c == nil {
		return nil, false
	}

	for _, track := range c.Tracks {
		if track.Control() == trackControl {
			return track, true
		}
	}

	return nil, false
}

func (c *StreamPusher) RangeTrack(f func(track *PusherTrack)) {
	if c == nil {
		return
	}

	var tracks = c.Tracks
	for _, track := range tracks {
		f(track)
	}
}

func (c *StreamPusher) Close() {
	for _, track := range c.Tracks {
		track.Close()
	}

	c.session.Close()
}
